/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: TradeFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.ui;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bhex.depth.DepthData;
import com.bhex.depth.DepthView;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.view.WheelView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.kline.bean.PriceDigits;
import io.bhex.app.main.ui.MainActivity;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.trade.adapter.BookListAdapter;
import io.bhex.app.trade.bean.BookListBean;
import io.bhex.app.trade.listener.BookClickListener;
import io.bhex.app.trade.presenter.BaseTradeFragmentPresenter;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.BookListView;
import io.bhex.app.view.BookView;
import io.bhex.app.view.ClickProxy;
import io.bhex.app.view.InnerRecyclerView;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.PopWindowList;
import io.bhex.app.view.PriceEditView;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.app.view.StepView;
import io.bhex.app.view.TopBar;
import io.bhex.app.view.anim.AnimUtils;
import io.bhex.app.view.bean.Book;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.DevicesUtil;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.TickerBean;

/**
 * ================================================
 * 描   述：交易
 * ================================================
 */
public abstract class BaseTradeFragment<P extends BaseTradeFragmentPresenter<V>, V extends BaseTradeFragmentPresenter.BaseTradeFragmentUI> extends BaseFragment<P, V> implements BaseTradeFragmentPresenter.BaseTradeFragmentUI, StepView.StepViewProgressListener, View.OnClickListener, BaseQuickAdapter.RequestLoadMoreListener, BookListView.OnBookListViewClikcLintener, OnRefreshListener {

    private static final String TAG = "";
    //book默认条数
    private static final int BOOK_LIST_DEFAULT_NUM = 10;
    //book默认显示条数
    private static final int BOOK_LIST_DEFAULT_VISIBLE_NUM = 6;
    private StepView stepView;
    private BookListView bookListView;
    List<Book> bidBooks = new ArrayList<>();
    List<Book> askBooks = new ArrayList<>();
    private RelativeLayout tab;
    protected View headerView;
    protected RecyclerView recyclerView;
    protected String baseToken = "";
    protected String quoteToken = "";
    protected String baseTokenAsset = "";
    protected String quoteTokenAsset = "";
    protected String symbol = "";
    protected String exchangeId = "";
    private String mergeDigitsStr = "";
    private boolean isFavorite;
    private boolean bSetFirstPrice = false;
    /**
     * 顶部买卖tab
     ****/
    //默认为买
    protected boolean isBuyMode = true;
    private TextView buyTabTx;
    private TextView sellTabTx;
    private View buyTabIndicator;
    private View sellTabIndicator;
    //默认是限价
    protected boolean isLimitedPrice = true;
    //下单价格模式 限价/市价
    protected TextView priceMode;
    private String[] priceModeArray;
    //市场价
    protected TextView priceMarketTx;
    //限价
    protected PriceEditView priceLimitedView;
    //盘口深度合并位数
//    private TextView digitMode;
    List<PriceDigits.DigitsItem> digitsList = new ArrayList<>();
    //盘口布局显示模式
//    private TextView bookListShowMode;
    private String[] bookListShowModeArray;
    protected Button btnCreateOrder;
    protected CoinPairBean coinPairBean;
    protected TopBar topBar;
    //数量经度
    private String basePrecision;
    //价格经度
    private String quotePrecision;
    //每次价格变动，最小的变动单位
    private String minPricePrecision;
    //最小交易数量
    private String minTradeQuantity;
    //最小交易额
    private String minTradeAmount;
    //价格保留位数
    protected int digitPrice;
    //数量保留位数
    protected int digitBase;
    //数量输入框
    protected EditText editAmount;
    protected TextView bookTitleAmount;
    protected TextView bookTitlePrice;
    protected TextView balanceAvailableTx;
    protected TextView stepViewMinTx;
    protected TextView stepViewMaxTx;
    protected String stepViewMaxValue;
    //购买计算单位
    protected boolean isQuoteToken = true;
    protected TextView priceAbout;
    private PopWindowList popListView;
    private String digitDepth = AppData.Config.DIGIT_DEPTH_DEFAULT;
    private PopWindowList popListViewOfPriceMode;
    private PopWindowList popListViewOfBookList;
    protected String baseTokenName = "";
    protected String quoteTokenName = "";
    private InnerRecyclerView bookListRv;
    private List<BookListBean> bookListData = new ArrayList<>();
    private BookListAdapter bookListAdapter;
    //默认首次加载币对
    protected boolean isFirst = true;
    private OptionsPickerView pvOptions;
    private List<String> bookShowModeList;
    private List<String> digitsNameList;
    private RelativeLayout buyTabRela;
    private RelativeLayout sellTabRela;
    protected RelativeLayout editAmountRela;
    protected TextView editAmountUnit;

    private int oldY = -1;
    private View footerView;
    //订单操作sheet行为
    private String[] orderSheetArray;
    private LinearLayout rootView;
    private AlertView orderAction;
    private AlertView priceAlertView;
    protected View buySellTabBg;
    private PointLengthFilter pricePointFilter;
    private PointLengthFilter amountPointFilter;
    protected int digitAmount;
    protected TickerBean currentTicker;
    protected SmartRefreshLayout refreshLayout;
    private int mSelectOption1;
    private int mSelectOption2;
    protected SkinTabLayout tabLayout;
    private NestedScrollView nestedScrollView;

    private HomeTradeControl mHomeControl;
    protected TextView balanceAvailableAboutTx;
    private View triggerPriceRela;
    protected View btnTransfer;

    public void setDefalutCoinPair(CoinPairBean coinpair){
//        coinPairBean = coinpair;
    }

    public void setHomeControl(HomeTradeControl control){
        mHomeControl = control;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_trade_layout, null, false);
    }

    @Override
    public void showSocketError(String error) {
        if (BuildConfig.DEBUG) {
            viewFinder.textView(R.id.socketTips).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.socketTips).setText("error: "+error);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        pricePointFilter = new PointLengthFilter();
        amountPointFilter = new PointLengthFilter();
        priceModeArray = new String[]{getResources().getString(R.string.string_limited_price), getResources().getString(R.string.string_market_price)};
        orderSheetArray = new String[]{getString(R.string.string_revoke_all_orders), getString(R.string.string_look_all_order)};
        bookListShowModeArray = new String[]{getResources().getString(R.string.string_show_default), getResources().getString(R.string.string_show_buy_order), getResources().getString(R.string.string_show_sell_order)};
        bookShowModeList = new ArrayList<>();
        bookShowModeList.add(getResources().getString(R.string.string_show_default));
        bookShowModeList.add(getResources().getString(R.string.string_show_buy_order));
        bookShowModeList.add(getResources().getString(R.string.string_show_sell_order));

        //标题栏
        topBar = viewFinder.find(R.id.topBar);
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        topBar.setRightTextMargin(0,PixelUtils.dp2px(0));
        topBar.setRightImg(R.mipmap.icon_kline);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(exchangeId) && !TextUtils.isEmpty(symbol)) {
                    IntentUtils.goKline(getActivity(), coinPairBean);
                }
            }
        });

        rootView = viewFinder.find(R.id.rootView);
//        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        refreshLayout = viewFinder.find(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);
        //LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        headerView = viewFinder.find(R.id.header_trade_layout);
        //footerView = layoutInflater.inflate(R.layout.footer_trade_layout, null);

        stepView = headerView.findViewById(R.id.stepView);
        bookListView = headerView.findViewById(R.id.bookListView);
        bookListView.setOnItemLintener(this);
        tab = headerView.findViewById(R.id.tab);
        buyTabRela = headerView.findViewById(R.id.tab_bid_rela);
        sellTabRela = headerView.findViewById(R.id.tab_ask_rela);
        buySellTabBg = headerView.findViewById(R.id.tab_bg);
        buyTabTx = headerView.findViewById(R.id.tab_bid);
        sellTabTx = headerView.findViewById(R.id.tab_ask);
        buyTabIndicator = headerView.findViewById(R.id.tab_indicator_bid);
        sellTabIndicator = headerView.findViewById(R.id.tab_indicator_ask);

        btnCreateOrder = headerView.findViewById(R.id.btn_create_order);
        priceAbout = headerView.findViewById(R.id.priceAbout);
        priceMode = headerView.findViewById(R.id.priceMode);
        priceMarketTx = headerView.findViewById(R.id.priceMarket);
        priceLimitedView = headerView.findViewById(R.id.priceLimitedEditView);
        priceLimitedView.setHintText(getString(R.string.string_price_input_hint_format, quoteTokenName));

        editAmountRela = headerView.findViewById(R.id.edit_amount_rela);
        editAmount = headerView.findViewById(R.id.edit_amount);
        btnTransfer = headerView.findViewById(R.id.btnTransfer);

        priceLimitedView.getPriceEt().setFilters(new InputFilter[]{pricePointFilter});
        editAmount.setFilters(new InputFilter[]{amountPointFilter});


        editAmountUnit = headerView.findViewById(R.id.edit_amount_unit);
        editAmount.addTextChangedListener(new AmountTextWatcher());
        bookTitleAmount = headerView.findViewById(R.id.title_amount);
        bookTitlePrice = headerView.findViewById(R.id.title_price);
        ShadowDrawable.setShadow(priceLimitedView);
        ShadowDrawable.setShadow(priceMarketTx);
        ShadowDrawable.setShadow(editAmountRela);
        tabLayout = headerView.findViewById(R.id.tabLayout);

        balanceAvailableTx = headerView.findViewById(R.id.balance_available);
        balanceAvailableAboutTx = headerView.findViewById(R.id.balance_available_about);
        stepViewMinTx = headerView.findViewById(R.id.stepView_minTxt);
        stepViewMaxTx = headerView.findViewById(R.id.stepView_maxTxt);

        //委托
        recyclerView = viewFinder.find(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        nestedScrollView = viewFinder.find(R.id.trade_scrollLayout);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {

            }
           public void onScrolled(RecyclerView recyclerView, int dx, int dy){

                /*if(mHomeControl != null) {
                    final int offset = recyclerView.computeVerticalScrollOffset();
                    final int range = recyclerView.computeVerticalScrollRange() - recyclerView.computeVerticalScrollExtent();

                    if (offset > PixelUtils.dp2px(50)) {
                        mHomeControl.OnShowTab(false);
                    }else if( offset ==0 ){
                        mHomeControl.OnShowTab(true);
                    }
                }*/
           }
        });

        initInstanceView();

        Bundle bundle = getArguments();
        if (bundle != null) {
            CoinPairBean bean = (CoinPairBean) bundle.getSerializable(AppData.INTENT.SYMBOLS);
            if(bean != null){
                coinPairBean = bean;
            }

        }
        if(coinPairBean != null)
            loadDefaultConfig(coinPairBean);
        //切换默认买入Tab
        switchBuySellTab(isBuyMode);
        switchPriceMode(isLimitedPrice);

        bookListRv = headerView.findViewById(R.id.bookList);
        LinearLayoutManager linearEmpty = new LinearLayoutManager(getActivity());
        linearEmpty.setOrientation(LinearLayoutManager.VERTICAL);
        bookListRv.setLayoutManager(linearEmpty);
        initBookListRvAdapter();

        if(isBuyMode == false) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
                }
            }, 50);
        }
    }

    abstract void initInstanceView();
    /**
     * 初始化booklist适配器
     */
    private void initBookListData(){
        bookListData.clear();
        askBooks.clear();
        bidBooks.clear();
        for (int i = 0; i < BOOK_LIST_DEFAULT_NUM; i++) {
            BookListBean bookListBean = new BookListBean(BookListBean.TYPE_BOOK);
            Book book1 = new Book();
            book1.setBid(false);
            book1.setPrice(getString(R.string.string_placeholder));
            book1.setPriceColor(getResources().getColor(R.color.red));
            book1.setVolume(getString(R.string.string_placeholder));
            book1.setProgressColor(getResources().getColor(R.color.red10));
            book1.setProgress(0f);
            book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
            bookListBean.setBook(book1);
            bookListData.add(bookListBean);
            askBooks.add(book1);

        }
        BookListBean bookListBean = new BookListBean(BookListBean.TYPE_LASTPRICE);
        bookListBean.setLastPrice(getString(R.string.string_placeholder));
        bookListBean.setLegalPrice(getString(R.string.string_placeholder));
        bookListData.add(bookListBean);

        for (int i = 0; i < BOOK_LIST_DEFAULT_NUM; i++) {
            BookListBean bookListBean2 = new BookListBean(BookListBean.TYPE_BOOK);
            Book book1 = new Book();
            book1.setBid(true);
            book1.setPrice(getString(R.string.string_placeholder));
            book1.setPriceColor(getResources().getColor(R.color.green));
            book1.setVolume(getString(R.string.string_placeholder));
            book1.setProgressColor(getResources().getColor(R.color.green10));
            book1.setProgress(0f);
            book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
            bookListBean2.setBook(book1);
            bookListData.add(bookListBean2);
            bidBooks.add(book1);

        }
    }
    private void initBookListRvAdapter() {

        initBookListData();

        bookListAdapter = new BookListAdapter(bookListData, new BookClickListener() {
            @Override
            public void onItemClick(View view,String price) {
                //点击挂单条目，赋值价格
                setPrice(price);
                AnimUtils.onScaleAnimation(priceLimitedView.getPriceEt());

            }
        });
        bookListRv.setAdapter(bookListAdapter);
        bookListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.btn_setting) {
                    showBookSetting();
                }
            }
        });
/*        if (Build.VERSION.SDK_INT >= 23) {
            bookListRv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(scrollY * 2 == (BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM) *v.getHeight()){

                        bookListRv.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_CANCEL, 0, 0, 0));
                    }
                }
            });
        }
        bookListRv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_CANCEL:
                        //setSelection(Integer.MAX_VALUE / 2);
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });*/

       /* LinearLayoutManager linearLayoutManager = new
                LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false);
        bookListRv.setLayoutManager(linearLayoutManager);

        CustomSnapHelper mMySnapHelper = new CustomSnapHelper();
        mMySnapHelper.attachToRecyclerView(bookListRv);*/

        bookListRv.setOnFlingListener(new RecyclerView.OnFlingListener() {
            @Override
            public boolean onFling(int velocityX, int velocityY) {
                int height = bookListRv.getMeasuredHeight();
                int first = bookListRv.getChildLayoutPosition(bookListRv.getChildAt(0));
                if (velocityY < 0 && first >= 5) {
                    bookListRv.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                        }
                    });
                } else if (velocityY > 0 && first <= 5) {
                    bookListRv.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                        }
                    });
                }
                return false;
            }
        });
        srollBookDefault();
    }

    /**
     * 盘口列表滑动至中间
     */
    private void srollBookDefault() {
        if (bookListRv != null&&bookListAdapter!=null) {
            bookListRv.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);
                }
            }, 100);
        }
    }

    @Override
    public boolean isSelected(){
        if(mHomeControl != null){
            return mHomeControl.IsSelected();
        }

        Bundle arguments = getArguments();
        boolean isSelect = true;
        if (arguments != null) {
            isSelect = arguments.getBoolean("isSelect",true);
        }
        return isSelect;
    }
    /**
     * 盘口设置
     */
    private void showBookSetting() {
        KeyBoardUtil.closeKeybord(editAmount, getContext());
        pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                mSelectOption1 = options1;
                mSelectOption2 = option2;
                bookListView.resetBookList(false);
                if (options1 == 0) {
                    //切换到:默认
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM - BOOK_LIST_DEFAULT_VISIBLE_NUM);

//                    bookListShowMode.setText(bookShowModeList.get(options1));
                } else if (options1 == 1) {
                    //切换到:显示买单
                    scrollToPosition(bookListRv, BOOK_LIST_DEFAULT_NUM);

//                    bookListShowMode.setText(bookShowModeList.get(options1));
                } else if (options1 == 2) {
                    //切换到:显示卖单
                    scrollToPosition(bookListRv, 0);
//                    bookListShowMode.setText(bookShowModeList.get(options1));
                }

                if (!digitsList.isEmpty()) {

                    //深度小数通知
                    digitDepth = digitsList.get(option2).getDigits();
//                    String digitsName = digitsList.get(option2).getDigitsName();
//                    viewFinder.textView(R.id.digit).setText(digitsName);
                    getPresenter().changeMergeDigit(digitDepth);
                }
            }
        })
                .setSubmitText(getResources().getString(R.string.string_sure))//确定按钮文字
                .setCancelText(getResources().getString(R.string.string_cancel))//取消按钮文字
//                    .setTitleText("盘口设置")//标题
                .setSubCalSize(16)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))//标题文字颜色
                .setSubmitColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.green_night : R.color.green))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.color_bg_2_night : R.color.color_bg_2))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.color_bg_2_night : R.color.color_bg_2))//滚轮背景颜色 Night mode
                .setDividerColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.divider_line_color_night : R.color.divider_line_color))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(14)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark))
                .setTextColorOut(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.grey2))
                .setLineSpacingMultiplier(2.5f)
                .setTypeface(Typeface.DEFAULT_BOLD)
//                .setTextXOffset(10,30,50)
//                            .setLinkage(false)//设置是否联动，默认true
//                    .setLabels("显示", "小数", "")//设置选择的三级单位
//                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .build();

        pvOptions.setNPicker(bookShowModeList, digitsNameList, null);//添加数据源
        pvOptions.setSelectOptions(mSelectOption1,mSelectOption2);
        pvOptions.show();
    }

    /**
     * 更新单位
     */

    protected abstract void updateUnit();

    /**
     * 更新步长进度条大小范围
     *
     * @param isQuoteToken
     * @param token
     * @param tokenName
     */
    protected abstract void updateStepViewRange(boolean isQuoteToken, String token, String tokenName);

    protected String getQuoteTokenAsset() {
        return quoteTokenAsset;
    }

    protected String getBaseTokenAsset() {
        String baseAsset = baseTokenAsset;
        return baseAsset;
    }

    /**
     * 加载币对默认配置
     *
     * @param mCoinPairBean
     */
    protected void loadDefaultConfig(CoinPairBean mCoinPairBean) {
        if (mCoinPairBean != null&&mCoinPairBean.baseTokenFutures==null) {
            coinPairBean = mCoinPairBean;
            isBuyMode = mCoinPairBean.isBuyMode();
            symbol = mCoinPairBean.getSymbolId();
            baseToken = mCoinPairBean.getBaseTokenId();
            quoteToken = mCoinPairBean.getQuoteTokenId();
            baseTokenName = mCoinPairBean.getBaseTokenName();
            quoteTokenName = mCoinPairBean.getQuoteTokenName();
            if (!TextUtils.isEmpty(mCoinPairBean.getSymbolName())) {
                topBar.setTitle(mCoinPairBean.getBaseTokenName() + "/" + mCoinPairBean.getQuoteTokenName());
            }
            priceLimitedView.setHintText(getString(R.string.string_price_input_hint_format, quoteTokenName));
            exchangeId = mCoinPairBean.getExchangeId();
            mergeDigitsStr = mCoinPairBean.getDigitMerge();
            handleMegeDigitData(mergeDigitsStr);
            isFavorite = SymbolDataManager.GetInstance().isFavorite(coinPairBean);
            basePrecision = mCoinPairBean.getBasePrecision();
            quotePrecision = mCoinPairBean.getQuotePrecision();
            minPricePrecision = mCoinPairBean.getMinPricePrecision();
            digitDepth = minPricePrecision;
            minTradeQuantity = mCoinPairBean.getMinTradeQuantity();
            minTradeAmount = mCoinPairBean.getMinTradeAmount();
            digitBase = NumberUtils.calNumerCount(getActivity(), basePrecision);
            digitPrice = NumberUtils.calNumerCount(getActivity(), minPricePrecision);
            digitAmount = NumberUtils.calNumerCount(getActivity(), quotePrecision);
            pricePointFilter.setDecimalLength(digitPrice);
            amountPointFilter.setDecimalLength(digitBase);

            //重置view数据状态

            priceLimitedView.setPrice("");
            editAmount.setText("");
            stepView.setStepProgress(0f);
            srollBookDefault();
            setFirstPrice();
            mSelectOption1=0;
            mSelectOption2=0;
            //合并小数位数-初始化位数联动处理
            if (digitsList != null) {
                if (!digitsList.isEmpty()) {
                    for (PriceDigits.DigitsItem digitsItem : digitsList) {
                        String digits = digitsItem.getDigits();
                        if (!TextUtils.isEmpty(minPricePrecision)&&!TextUtils.isEmpty(digits)) {
                            if (minPricePrecision.equals(digits)) {
                                mSelectOption2 = digitsList.indexOf(digitsItem);
                                break;
                            }
                        }
                    }
                }
            }

        } else {
//            ToastUtils.showShort(getString(R.string.string_net_exception));
        }
    }

    @Override
    public int getDigitBase() {
        return digitBase;
    }

    @Override
    public String getQuoteToken() {
        return quoteToken;
    }

    @Override
    public String getBaseToken() {
        return baseToken;
    }

    private void handleMegeDigitData(String mergeDigitsStr) {
        if (!TextUtils.isEmpty(mergeDigitsStr)) {
            String[] digitsArray = mergeDigitsStr.split(",");
            if (digitsArray.length > 0) {
                digitsList.clear();
                for (String s : digitsArray) {
                    PriceDigits.DigitsItem digitsItem = new PriceDigits.DigitsItem();
                    String name = NumberUtils.calNumerName(getActivity(), s);
                    digitsItem.setDigitsName(name);
                    digitsItem.setDigits(s);
                    digitsList.add(digitsItem);
                }
                String[] itemNames = new String[digitsList.size()];
                for (int i = 0; i < digitsList.size(); i++) {
                    itemNames[i] = digitsList.get(i).getDigitsName();
                }

                digitsNameList = Arrays.asList(itemNames);
            }

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        switchBuySellTab(isBuyMode);

        ShadowDrawable.setShadow(priceLimitedView);
        ShadowDrawable.setShadow(priceMarketTx);
        ShadowDrawable.setShadow(editAmountRela);
    }

    PriceAddRunnable priceAddRunnable = new PriceAddRunnable();
    PriceMinusRunnable priceMinusRunnable = new PriceMinusRunnable();

    /**
     * 盘口item点击
     *
     * @param book
     */
    @Override
    public void onClick(Book book) {
        DevicesUtil.vibrate(getActivity(), 200);

        if (book != null) {
            String price = book.getPrice();
            setPrice(price);
        }
    }

    /**
     * 设置第一次价格
     * @param
     */
    private void setFirstPrice() {

        priceLimitedView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (currentTicker != null ) {
                    String symbol = currentTicker.getS();
                    if (!TextUtils.isEmpty(symbol)){

                        if (symbol.equals(getSymbols()) && bSetFirstPrice == false) {
                            setPrice(currentTicker.getC());
                            bSetFirstPrice = true;
                        }
                    }

                }
            }
        },500);
    }

    /**
     * 设置价格
     *
     * @param price
     */
    private void setPrice(String price) {
        if (TextUtils.isEmpty(price)) {
            price = "";
        }
        if (price.contains("-")) {
            price = "";
        }
        priceLimitedView.setPrice(price);
        setPriceAbout(price);
    }

    /**
     * 设置价格估值
     * @param price
     */
    private void setPriceAbout(String price){
        if (TextUtils.isEmpty(price)) {
            price = "";
        }
        if (price.contains("-")) {
            price = "";
        }
        if (!TextUtils.isEmpty(price)) {
            String legalMoney = RateDataManager.CurRatePrice(quoteToken, price);
            legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
            priceAbout.setText("≈"+legalMoney);
        } else {
            priceAbout.setText(getString(R.string.string_placeholder));
        }
    }

    /**
     * 设置交易量/额
     *
     * @param value
     */
    private void setAmount(String value) {
        editAmount.setText(value);
    }

    /**
     * 数量输入框监听器
     */
    class AmountTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateStepViewValue(s.toString());
            updateTradeAmountOfMoney();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * 更新步长值
     *
     * @param valueStr
     */
    protected void updateStepViewValue(String valueStr) {
        if (TextUtils.isEmpty(valueStr) || TextUtils.isEmpty(stepViewMaxValue)) {
            stepView.setStepProgress(0);
        } else {
            float progress = Float.valueOf(NumberUtils.div(stepViewMaxValue, valueStr, 2) + "");
            stepView.setStepProgress(progress);
        }
    }

    /**
     * 价格输入框监听
     */
    class PriceEditViewListener implements PriceEditView.PriceViewListener {

        @Override
        public void onClickPlus() {
            priceAdd();
        }

        @Override
        public void onClickMinusSign() {
            priceMinus();
        }

        @Override
        public void onPressPlusStart() {
            priceLimitedView.postDelayed(priceAddRunnable, 50);
        }

        @Override
        public void onPressPlusEnd() {
            priceLimitedView.removeCallbacks(priceAddRunnable);
        }

        @Override
        public void onPressMinusSignStart() {
            priceLimitedView.postDelayed(priceMinusRunnable, 50);
        }

        @Override
        public void onPressMinusSignEnd() {
            priceLimitedView.removeCallbacks(priceMinusRunnable);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setPriceAbout(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            updateTradeAmountOfMoney();
            updateUnit();
        }

    }

    class PriceAddRunnable implements Runnable {

        @Override
        public void run() {
            priceAdd();
            priceLimitedView.removeCallbacks(priceAddRunnable);
            priceLimitedView.postDelayed(priceAddRunnable, 50);
        }
    }

    class PriceMinusRunnable implements Runnable {

        @Override
        public void run() {
            priceMinus();
            priceLimitedView.removeCallbacks(priceMinusRunnable);
            priceLimitedView.postDelayed(priceMinusRunnable, 50);
        }
    }

    /**
     * 价格++
     */
    private void priceAdd() {
        if (TextUtils.isEmpty(minPricePrecision)) {
            DebugLog.w(TAG, "minPricePrecision is null");
            return;
        }
        String currentPrice = priceLimitedView.getPrice();
        if (TextUtils.isEmpty(currentPrice)) {
            currentPrice = "0";
        }
        double result = NumberUtils.add(currentPrice, minPricePrecision);
        if (result < 0) {
            result = 0;
        }
        String price = NumberUtils.roundFormatDown(result, NumberUtils.calNumerCount(getActivity(), minPricePrecision));
        setPrice(price);
        updateTradeAmountOfMoney();
    }

    /**
     * 价格++
     */
    private void priceMinus() {
        if (TextUtils.isEmpty(minPricePrecision)) {
            DebugLog.w(TAG, "minPricePrecision is null");
            return;
        }
        String currentPrice = priceLimitedView.getPrice();
        if (TextUtils.isEmpty(currentPrice)) {
            currentPrice = "0";
        }
        double result = NumberUtils.sub(currentPrice, minPricePrecision);
        if (result < 0) {
            result = 0;
        }
        String price = NumberUtils.roundFormatDown(result, NumberUtils.calNumerCount(getActivity(), minPricePrecision));
        setPrice(price);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        stepView.setOnProgressListener(this);
        stepView.setStepTouchListener(new StepView.StepTouchListener() {
            @Override
            public void onTouchDown() {
                priceLimitedView.setPriceFocusableInTouchMode(false);
                //editAmount.setFocusable(false);
                //editAmount.setFocusableInTouchMode(false);
            }

            @Override
            public void onTouchUp() {
                //editAmount.setFocusable(true);
                //editAmount.setFocusableInTouchMode(true);
                priceLimitedView.setPriceFocusableInTouchMode(true);
            }
        });
        headerView.findViewById(R.id.tab_bid_rela).setOnClickListener(this);
        headerView.findViewById(R.id.tab_ask_rela).setOnClickListener(this);
        headerView.findViewById(R.id.priceModeRela).setOnClickListener(this);
        headerView.findViewById(R.id.revoke_all_orders).setOnClickListener(this);
        headerView.findViewById(R.id.order_all_linear).setOnClickListener(this);
        headerView.findViewById(R.id.edit_amount).setOnClickListener(this);
        headerView.findViewById(R.id.order_actionsheet).setOnClickListener(this);
        //footerView.findViewById(R.id.look_all_order).setOnClickListener(this);
        priceLimitedView.setPriceViewListener(new PriceEditViewListener());

        //book列表滑动监听
        bookListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(bookListRv, mToPosition);
                }
            }
        });

        //下单
        btnCreateOrder.setOnClickListener(new ClickProxy(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DevicesUtil.vibrate(getActivity(), 100);

                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    createOrder(isBuyMode);
                }
            }
        }));
    }

    /**
     * 切换买卖tab
     *
     * @param isBuyModeParam
     */
    protected void switchBuySellTab(boolean isBuyModeParam) {
        isBuyMode = isBuyModeParam;
        editAmount.setText("");
        if (isBuyMode) {
            buyTabTx.setTextColor(getResources().getColor(R.color.green));
            sellTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
//            buyTabRela.setBackgroundResource(R.drawable.bg_corner_rect_green);
//            sellTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_green);
            //AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
        } else {
            buyTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            sellTabTx.setTextColor(getResources().getColor(R.color.red));
//            sellTabRela.setBackgroundResource(R.drawable.bg_corner_rect_red);
//            buyTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_red);
            //AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
        }

        updateUnit();
        updateBuySellTabAssociatedView(isBuyMode);
        updateInputPointLength();


    }

    /**
     * 切换买卖tab
     *
     * @param isBuyModeParam
     * @param btnBuyText 按钮买文案
     * @param btnSellText 按钮卖文案
     */
    protected void switchBuySellTab(boolean isBuyModeParam,String btnBuyText,String btnSellText) {
        isBuyMode = isBuyModeParam;
        editAmount.setText("");
        buyTabTx.setText(btnBuyText);
        sellTabTx.setText(btnSellText);
        if (isBuyMode) {
            buyTabTx.setTextColor(getResources().getColor(R.color.green));
            sellTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
//            buyTabRela.setBackgroundResource(R.drawable.bg_corner_rect_green);
//            sellTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_green);
            //AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);
        } else {
            buyTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            sellTabTx.setTextColor(getResources().getColor(R.color.red));
//            sellTabRela.setBackgroundResource(R.drawable.bg_corner_rect_red);
//            buyTabRela.setBackgroundResource(R.color.white);
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_red);
            //AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());
        }

        updateUnit();
        updateContractBuySellTabAssociatedView(isBuyMode,btnBuyText,btnSellText);
        updateInputPointLength();


    }

    /**
     * 更新价格数量输入框的小数位数长度限制
     */
    private void updateInputPointLength() {
        pricePointFilter.setDecimalLength(digitPrice);
        if (isBuyMode && !isLimitedPrice) {
            amountPointFilter.setDecimalLength(digitAmount);
        } else {
            amountPointFilter.setDecimalLength(digitBase);
        }
    }

    /**
     * 设置背景和阴影
     *
     * @param view
     */
    private void setShadow(View view) {
        ShadowDrawable.setShadowDrawable(view,
//                getResources().getColor(R.color.white),
                PixelUtils.dp2px(2),
                getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark10_night : R.color.dark10),
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }

    /**
     * 更新可用资产
     *
     * @param token
     * @param tokenName
     */
    protected void updateAsset(String token, String tokenName) {
        String assetAvaliableOfToken = "";
        int digit = AppData.Config.DIGIT_DEFAULT_VALUE;
        if (token != null && token.equalsIgnoreCase(quoteToken)) {
            assetAvaliableOfToken = getQuoteTokenAsset();
            digit = digitPrice;
        }
        else {
            assetAvaliableOfToken = getBaseTokenAsset();
            digit = digitBase;
        }

        String available = NumberUtils.roundFormatDown(assetAvaliableOfToken, AppData.Config.DIGIT_DEFAULT_VALUE);
        if (!TextUtils.isEmpty(available)) {
            if (available.contains(".") && available.length() > 12) {
                available = available.substring(0, 12);
            }
        }else{
            available = NumberUtils.roundFormatDown("0", AppData.Config.DIGIT_DEFAULT_VALUE);
        }
        balanceAvailableTx.setText(getString(R.string.string_balance_available_format, NumberUtils.roundFormatDown(String.valueOf(available), digit), tokenName));

        String legalMoney = RateDataManager.CurRatePrice(token, assetAvaliableOfToken);
        legalMoney = RateDataManager.getShowLegalMoney(legalMoney, digitAmount);

        balanceAvailableAboutTx.setText("≈" + legalMoney);
    }

    /**
     * 更新买卖tab改变相关的View状态 标识
     *
     * @param isBuyMode
     */
    protected void updateBuySellTabAssociatedView(boolean isBuyMode) {
        //更新下单按钮状态
        btnCreateOrder.setBackgroundResource(isBuyMode ? R.drawable.bg_corner_green : R.drawable.bg_corner_red);
        if (!UserInfo.isLogin()) {
            btnCreateOrder.setText(getString(R.string.string_login));
        } else {
            if (isBuyMode) {
                btnCreateOrder.setText(getString(R.string.string_purchase) + " " + baseTokenName);
            } else {
                btnCreateOrder.setText(getString(R.string.string_sellout) + " " + baseTokenName);
            }
        }

        //更新步长进度条的颜色
//        int colorGray, colorGreen, colorRed, colorWhite, colorDark;
//        colorGray = getResources().getColor(R.color.divider_line_color);
//        colorGreen = getResources().getColor(R.color.color_green);
//        colorRed = getResources().getColor(R.color.color_red);
//        colorWhite = getResources().getColor(R.color.color_bg_2);
//        colorDark = getResources().getColor(R.color.divider_line_color_night);
//
//        if (!CommonUtil.isBlackMode()) {//白色版
//            if (isBuyMode) {
//                stepView.changeColor(colorGray, colorGreen, colorGray, colorGreen, colorWhite);
//            } else {
//                stepView.changeColor(colorGray, colorRed, colorGray, colorRed, colorWhite);
//            }
//        } else {//夜间版
//            if (isBuyMode) {
//                stepView.changeColor(colorDark, colorGreen, colorDark, colorGreen, colorDark);
//            } else {
//                stepView.changeColor(colorDark, colorRed, colorDark, colorRed, colorDark);
//            }
//        }


    }

    /**
     * 更新买卖tab改变相关的View状态 标识
     *
     * @param isBuyMode
     */
    protected void updateContractBuySellTabAssociatedView(boolean isBuyMode,String openTxt,String closeTxt) {
        //更新下单按钮状态
        btnCreateOrder.setBackgroundResource(isBuyMode ? R.drawable.bg_corner_green : R.drawable.bg_corner_red);
        if (!UserInfo.isLogin()) {
            btnCreateOrder.setText(getString(R.string.string_login));
        } else {
            if (isBuyMode) {
                btnCreateOrder.setText(getString(R.string.string_purchase) + "("+openTxt+") " + baseTokenName);
            } else {
                btnCreateOrder.setText(getString(R.string.string_sellout) + "("+closeTxt+")" + baseTokenName);
            }
        }

        //更新步长进度条的颜色
//        int colorGray, colorGreen, colorRed, colorWhite, colorDark;
//        colorGray = getResources().getColor(R.color.divider_line_color);
//        colorGreen = getResources().getColor(R.color.color_green);
//        colorRed = getResources().getColor(R.color.color_red);
//        colorWhite = getResources().getColor(R.color.color_bg_2);
//        colorDark = getResources().getColor(R.color.divider_line_color_night);
//
//        if (!CommonUtil.isBlackMode()) {//白色版
//            if (isBuyMode) {
//                stepView.changeColor(colorGray, colorGreen, colorGray, colorGreen, colorWhite);
//            } else {
//                stepView.changeColor(colorGray, colorRed, colorGray, colorRed, colorWhite);
//            }
//        } else {//夜间版
//            if (isBuyMode) {
//                stepView.changeColor(colorDark, colorGreen, colorDark, colorGreen, colorDark);
//            } else {
//                stepView.changeColor(colorDark, colorRed, colorDark, colorRed, colorDark);
//            }
//        }


    }

    /**
     * 切换限价/市价
     *
     * @param isLimitedPriceParams
     */
    abstract protected void switchPriceMode(boolean isLimitedPriceParams) ;

    /**
     * 更新价格模式关联View
     *
     * @param isLimitedPrice
     */
    abstract protected void updatePriceModeAssociatedView(boolean isLimitedPrice);

    /**
     * 是否显示累计量
     * @param
     * @return
     */
    abstract public boolean isShowCumulativeVolume();

    /**
     * 是否是当前委托-买单的价格
     * @param price
     * @return
     */
    abstract public boolean isCurrentBidOrderPrice(String price);

    /**
     * 是否是当前委托-卖单的价格
     * @param price
     * @return
     */
    abstract public boolean isCurrentAskOrderPrice(String price);

    @Override
    public List<BookListBean> getBookListData() {
        return bookListData;
    }

    @Override
    public void updateBookList() {
        getActivity().runOnUiThread(() -> {
            bookListAdapter.notifyDataSetChanged();
        });
    }

    public void scrollToPosition(RecyclerView rv, int position) {
        if (position != -1) {
            smoothMoveToPosition(rv, position);
        } else {
            smoothMoveToPosition(rv, position + 1);
        }
    }

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @Override
    public void updateAssettByToken(String token, String asset) {
        if (!UserInfo.isLogin()){
            if (!balanceAvailableTx.getText().toString().equals(getString(R.string.string_placeholder))) {
                balanceAvailableTx.setText(getString(R.string.string_placeholder));
                balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
            }
            return;
        }
        //重新触发一次单位更新（里面包括可用资产、步长更新）
        if (token.equalsIgnoreCase(quoteToken))
            quoteTokenAsset = asset;
        else if (token.equalsIgnoreCase(baseToken))
            baseTokenAsset = asset;
        updateUnit();
    }

    @Override
    public void resetView() {
        priceAbout.setText(getString(R.string.string_placeholder));
        balanceAvailableTx.setText(getString(R.string.string_placeholder));
        balanceAvailableAboutTx.setText(getString(R.string.string_placeholder));
        updateLatestPrice(new TickerBean());
        initBookListData();
        bookListAdapter.notifyDataSetChanged();
        baseTokenAsset = "";
        quoteTokenAsset = "";
        bSetFirstPrice = false;
    }

    @Override
    public String getDigitStr() {
        return digitDepth;
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);

        if (visible) {
            priceLimitedView.refreshNightStyle();
            editAmount.setTextAppearance(this.getContext(), CommonUtil.isBlackMode() ? R.style.Body_Dark_Bold_night : R.style.Body_Dark_Bold);
            editAmount.setHintTextColor(SkinColorUtil.getDark50(this.getContext()));
//            stepView.setBgSmallCircleColor(SkinColorUtil.getGrey(this.getContext()),SkinColorUtil.getGrey(this.getContext()));
        }
    }

    /**
     * 更新最新价
     */
    protected void updateLatestPrice(TickerBean tickerBean) {
        currentTicker = tickerBean;
        if(bSetFirstPrice == false){
            setFirstPrice();
        }
        String legalMoney = RateDataManager.CurRatePrice(quoteToken, tickerBean.getC() + "");
        legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
        bookListView.updateLatestPrice(NumberUtils.roundingString(tickerBean.getC(), digitPrice), legalMoney, KlineUtils.getMarketViewColor(getActivity(), tickerBean.getC(), tickerBean.getO()));

        if (bookListData.size() >= BOOK_LIST_DEFAULT_NUM) {
            BookListBean bookListOfLastPrice = bookListData.get(BOOK_LIST_DEFAULT_NUM);
            bookListOfLastPrice.setLastPrice(NumberUtils.roundingString(tickerBean.getC(), digitPrice));
            bookListOfLastPrice.setLegalPrice(legalMoney);
            bookListOfLastPrice.setChange(String.valueOf(NumberUtils.sub(tickerBean.getC(),tickerBean.getO())));
//            bookListData.set(BOOK_LIST_DEFAULT_NUM,bookListOfLastPrice);
            bookListAdapter.notifyDataSetChanged();
            TextView rightTextView = topBar.getRightTextView();
            rightTextView.setVisibility(View.VISIBLE);
            rightTextView.setText(KlineUtils.calRiseFallRatio(tickerBean.getC(), tickerBean.getO()));
            rightTextView.setTextColor(KlineUtils.getMarketViewColor(getActivity(), tickerBean.getC(), tickerBean.getO()));
        }

    }


    @Override
    public void onStepViewProgress(float progress) {
        if (TextUtils.isEmpty(stepViewMaxValue)) {
            return;
        }
        priceLimitedView.setFocusable(true);
        double result = NumberUtils.mul(stepViewMaxValue, progress + "");
        String value = NumberUtils.roundFormatDown(String.valueOf(result), (isBuyMode&&!isLimitedPrice) ? digitAmount : digitBase);
        setAmount(value);
        updateTradeAmountOfMoney();
    }

    /**
     * 更新交易需要金额
     */
    abstract protected void updateTradeAmountOfMoney();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_amount:
                break;
            case R.id.tab_bid_rela:
                switchBuySellTab(true);
                AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);

                break;
            case R.id.tab_ask_rela:
                switchBuySellTab(false);
                AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());

                break;
            case R.id.priceModeRela:
                showPriceModeSelect();
                break;
            case R.id.look_all_order:
                if (!UserInfo.isLogin()) {
                    //去登录
                    IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                } else {
                    //全部订单
                    if(coinPairBean.baseTokenOption != null)
                        IntentUtils.goAllOptionOrders(getActivity());
                    else
                        IntentUtils.goAllOrders(getActivity());
                }
                break;
            case R.id.order_actionsheet:
                showOrderActionSheet();
                break;
        }
    }

    /**
     * 显示订单操作sheet
     */
    private void showOrderActionSheet() {
        KeyBoardUtil.closeKeybord(editAmount, getContext());
        if(coinPairBean != null)
            orderSheetArray[0] = getString(R.string.string_revoke_all_orders)+" "+ (coinPairBean.baseTokenOption != null? coinPairBean.getSymbolName():coinPairBean.getBaseTokenName()+"/"+coinPairBean.getQuoteTokenName());
        orderAction = new AlertView(null, null, getString(R.string.string_cancel), null, orderSheetArray, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position == 0) {
                    //全部撤单
                    if (!UserInfo.isLogin()) {
                        //去登录
                        IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                    } else {
                        //全部撤单
                        getPresenter().revokeAllOrders();
                    }
                }
                else if(position == 1){
                    if (!UserInfo.isLogin()) {
                        //去登录
                        IntentUtils.goLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TRADE);
                    } else {
                        if(coinPairBean.baseTokenOption != null)
                            IntentUtils.goAllOptionOrders(getActivity());
                        else
                            IntentUtils.goAllOrders(getActivity());
                    }
                }
            }
        });
        orderAction.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                ((MainActivity) getActivity()).removeBackKeyListener();
            }
        });
        orderAction.show();
        ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
            @Override
            public void onKeyBack() {
                orderAction.dismiss();
            }
        });
    }

    /**
     * 下单
     *
     * @param isBuyMode
     */
    protected abstract void createOrder(boolean isBuyMode);

    @Override
    public void createOrderSuccess() {
        priceLimitedView.setPrice("");
        editAmount.setText("");
    }

    /**
     * 显示价格模式选择
     */
    private void showPriceModeSelect() {
        KeyBoardUtil.closeKeybord(editAmount, getContext());

        priceAlertView = new AlertView(null, null, getString(R.string.string_cancel), null, priceModeArray, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position == 0) {
                    //切换到:限价
                    switchPriceMode(true);
                } else {
                    //切换到:市价
                    switchPriceMode(false);
                }
            }
        });

        priceAlertView.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                ((MainActivity) getActivity()).removeBackKeyListener();
            }
        });
        priceAlertView.show();
        ((MainActivity) getActivity()).registerBackKeyListener(new MainActivity.KeyBackListener() {
            @Override
            public void onKeyBack() {
                priceAlertView.dismiss();
            }
        });
    }



    @Override
    public String getExchangeId() {
        return exchangeId;
    }

    @Override
    public String getSymbols() {
        return symbol;
    }

    @Override
    public void showLatestPrice(TickerBean data) {
        updateLatestPrice(data);
    }



    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getPresenter().refresh();
        refreshLayout.finishRefresh(1000);
    }

    public class CustomSnapHelper extends LinearSnapHelper {
        private OrientationHelper mHorizontalHelper;

        @Override
        public int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView) {
            int[] out = new int[2];
            //判断支持水平滚动，修改水平方向的位置，是修改的out[0]的值
            if (layoutManager.canScrollVertically()) {
                out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
            } else {
                out[0] = 0;
            }
            return out;
        }

        private int distanceToStart(View targetView, OrientationHelper helper) {
            return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding();
        }

        @Override
        public View findSnapView(RecyclerView.LayoutManager layoutManager) {
            return findStartView(layoutManager, getHorizontalHelper(layoutManager));
        }

        private View findStartView(RecyclerView.LayoutManager layoutManager,
                                   OrientationHelper helper) {
            if (layoutManager instanceof LinearLayoutManager) {
                int firstChild = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                int lastChild = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                if (firstChild == RecyclerView.NO_POSITION) {
                    return null;
                }
                //这行的作用是如果是最后一个，翻到最后一条，解决显示不全的问题
                if (lastChild == layoutManager.getItemCount() - 1) {
                    return layoutManager.findViewByPosition(lastChild);
                }
                View child = layoutManager.findViewByPosition(firstChild);
                //获取偏左显示的Item
                if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2
                        && helper.getDecoratedEnd(child) > 0) {
                    return child;
                } else {
                    return layoutManager.findViewByPosition(firstChild + 1);
                }
            }
            return super.findSnapView(layoutManager);
        }

        private OrientationHelper getHorizontalHelper(
                RecyclerView.LayoutManager layoutManager) {
            if (mHorizontalHelper == null) {
                mHorizontalHelper = OrientationHelper.createVerticalHelper(layoutManager);
            }
            return mHorizontalHelper;
        }
    }


    public void getTicker(){
        if(getPresenter() != null)
            getPresenter().getTicker();
    }

    public void requestDepthData(){
        if(getPresenter() != null)
            getPresenter().requestDepthData();
    }

}
